package com.mutouren.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mutouren.common.exception.ExceptionUtils;

public class CookieUtils {
	
	public static void set(HttpServletResponse response, String name, String value, String path) {
		set(response, name, value, path, null);
	}
	
	public static void set(HttpServletResponse response, String name, String value, String path, Integer maxAge) {
		Cookie cookie = new Cookie(name, null);
		cookie.setPath(path);
		if (maxAge != null) {
			cookie.setMaxAge(maxAge);
		}
		cookie.setHttpOnly(true);
		
		try {
			cookie.setValue(URLEncoder.encode(value, "utf-8"));
		} catch (UnsupportedEncodingException e) {
			throw ExceptionUtils.doUnChecked(e);
		}
		response.addCookie(cookie);
	}
	
	public static String get(HttpServletRequest request, String name) {
		String value = null;
		Cookie[] cookies = request.getCookies();
		
		if (cookies == null) return null;
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(name)) {
				try {
					value = URLDecoder.decode(cookie.getValue(), "utf-8");
					break;
				} catch (UnsupportedEncodingException e) {
					throw ExceptionUtils.doUnChecked(e);
				}
			}
		}		
		return value;
	}
	
	public static void delete(HttpServletRequest request, HttpServletResponse response, String name, String path) {
		Cookie[] cookies = request.getCookies();
		
		if (cookies == null) return;
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(name)) {
				cookie.setMaxAge(0);
				cookie.setPath(path);
				response.addCookie(cookie);
				break;
			}
		}		
	}	
	
}
